$(document).ready(function() {
	var OpeoutObj="";
    var VAL ={
        NORMAL     : "0000000"  ,
        EVT_USER   : $("#userId").text(),
        T_XPINQBOX  : "XPINQBOX",
        T_XPBOXHLD  : "XPBOXHLD",
        T_XPBISOPE  : "XPBISOPE",
        QUERY_ALL   : false
    };
    var domObj = {
			$window : $(window),
			$holdDetailDiv : $("#holdDetailDiv"),
			$holdDetailGrd : $("#holdDetailGrd")
	};
    /**
     * All controls's jquery object/text
     * @type {Object}
     */
    var controlsQuery = {
        W                 : $(window)              ,
        ppBoxIDInput      : $("#ppBoxIDInput")     ,

        mainGrd   :{
            grdId     : $("#holdDetailGrd")   ,
            grdPgText : "#holdDetailPg"       ,
            fatherDiv : $("#holdDetailDiv")
        }
    };

    /**
     * All button's jquery object
     * @type {Object}
     */
    var btnQuery = {
        f1 : $("#f1_btn"),
        f7 : $("#f7_btn")
    };

    /**
     * All tool functions
     * @type {Object}
     */
    var toolFunc = {
        resetJqgrid :function(){
//            controlsQuery.W.unbind("onresize");
//            controlsQuery.mainGrd.grdId.setGridWidth(controlsQuery.mainGrd.fatherDiv.width()*0.90);
//            controlsQuery.W.bind("onresize", this);
        },
        clearInput : function(){
            controlsQuery.ppBoxIDInput.val("");
        },
        /**
         * Set data for select
         * @param dataCnt
         * @param arr
         * @param selVal
         * @param queryObj
         */
        setSelectDate : function(dataCnt, arr, selVal, queryObj){
            var i, realCnt;

            queryObj.empty();
            realCnt = parseInt( dataCnt, 10);

            if( realCnt == 1 ){
                if( arr.hasOwnProperty(selVal)){
                    queryObj.append("<option value="+ arr[selVal] +">"+ arr[selVal] +"</option>");
                }
            }else if( realCnt > 1 ){
                for( i = 0; i < realCnt; i++ ){
                    if( arr[i].hasOwnProperty(selVal)){
                        queryObj.append("<option value="+ arr[i][selVal] +">"+ arr[i][selVal] +"</option>");
                    }
                }
            }            
            queryObj.select2({
    	    	theme : "bootstrap"
    	    });
        },
        /**
         * 根据人员，厂别，站点的关系，筛选出可以使用的站点。By CMJ
         */
        iniOpeSelect : function(){
            var inObj;
            var user_id = VAL.EVT_USER;
            var iaryB = {
                user_id     : user_id
            }
            inObj = {
                trx_id      : VAL.T_XPBISOPE,
                action_flg  : 'I',
                iaryB       : iaryB
            };
            OpeoutObj = comTrxSubSendPostJson(inObj);
        }
    };

    /**
     * All button click function
     * @type {Object}
     */
    var btnFunc = {
        //Query
        f1_func : function(){
            var inObj,
                outObj,
                box_id;

            box_id = controlsQuery.ppBoxIDInput.val();
//            if(!box_id){
//                showErrorDialog("","请输入箱号！");
//                return false;
//            }

            inObj = {
                trx_id : VAL.T_XPBOXHLD,
                action_flg : "Q",
                box_id : box_id
            };
            
            outObj = comTrxSubSendPostJson(inObj);
            if (outObj.rtn_code == VAL.NORMAL) {
            	controlsQuery.mainGrd.grdId.jqGrid("clearGridData");
            	if(box_id != ""){
            		/**
        		     * 检查用户是否有权限操作这个箱子。By CMJ
        		     * @author CMJ
        		     */
            		VAL.QUERY_ALL = false;
                	if(outObj.box_stat=="HOLD"){
                		for(var i=0;i<OpeoutObj.tbl_cnt;i++){
            		    	var Opeoary = OpeoutObj.tbl_cnt>1 ? OpeoutObj.oary[i] : OpeoutObj.oary;
            		    	if($.trim(outObj.nx_ope_id_fk) == Opeoary.ope_id && 
            		    	   $.trim(outObj.nx_ope_ver_fk) == Opeoary.ope_ver){
            		    		setGridInfo(outObj.oary, "#holdDetailGrd");
            	                controlsQuery.ppBoxIDInput.val("");
            	                break;
            		    	}
                		}
                		if(OpeoutObj.tbl_cnt ==0 || i>=OpeoutObj.tbl_cnt){
            		    	showErrorDialog("", "此用户没有权限操作站点["+outObj.nx_ope_id_fk+"]的箱子！");
            			    return false; 
            		    }
                	}else{
                		showErrorDialog("", "箱子状态["+outObj.box_stat+"]无效,必须为[HOLD]！");
        			    return false; 
                	}
            	}else {
            		VAL.QUERY_ALL = true;
            		if(Object.prototype.toString.apply(outObj.oary1) == "[object Object]"){
            			var flg = false;
            			for(var i=0;i<OpeoutObj.tbl_cnt;i++){
            		    	var Opeoary = OpeoutObj.tbl_cnt>1 ? OpeoutObj.oary[i] : OpeoutObj.oary;
            		    	if($.trim(outObj.oary1.transaction.nx_ope_id_fk) == Opeoary.ope_id && 
            		    	   $.trim(outObj.oary1.transaction.nx_ope_ver_fk) == Opeoary.ope_ver){
            		    		flg = true;
            		    	}
                		}
            			if (flg){
            				rand_row_id = $.jgrid.randId();
        		    		controlsQuery.mainGrd.grdId.jqGrid('addRowData', rand_row_id, outObj.oary1.transaction.oary, "first");
            			}
            		}else {
            			for (var j=0;j<outObj.oary1.length;j++){
                			var flg = false;
                			for(var i=0;i<OpeoutObj.tbl_cnt;i++){
                		    	var Opeoary = OpeoutObj.tbl_cnt>1 ? OpeoutObj.oary[i] : OpeoutObj.oary;
                		    	if($.trim(outObj.oary1[j].nx_ope_id_fk) == Opeoary.ope_id && 
                		    	   $.trim(outObj.oary1[j].nx_ope_ver_fk) == Opeoary.ope_ver){
                		    		flg = true;
                		    	}
                    		}
                			if (flg){
                				if(Object.prototype.toString.apply(outObj.oary1[j].oary) == "[object Object]"){
                					rand_row_id = $.jgrid.randId();
                					controlsQuery.mainGrd.grdId.jqGrid('addRowData', rand_row_id, outObj.oary1[j].oary, "first");
                				}else {
                					for (var k=0;k<outObj.oary1[j].oary.length;k++){
                						rand_row_id = $.jgrid.randId();
                						controlsQuery.mainGrd.grdId.jqGrid('addRowData', rand_row_id, outObj.oary1[j].oary[k], "first");
                					}
                				}
                			}
                		}
            		}
            		
            	}
                
            }
        },
        //HOLD Release
        f7_func : function(){
            var inObj,
                outObj,
                box_id,
                hld_evt_seq,
                crGrid,
                rowIds,
                selRowDataNO,
                selRowData;

            crGrid = controlsQuery.mainGrd.grdId;
            rowIds = crGrid.jqGrid('getDataIDs');
            if(rowIds.length === 0 ){
                showErrorDialog("","请先输入箱号查询！");
                return false;
            }
            selRowDataNO = crGrid.jqGrid('getGridParam','selrow');
            if(!selRowDataNO){
                showErrorDialog("","请选择需要释放的记录！");
                return false;
            }

            selRowData = crGrid.jqGrid('getRowData', selRowDataNO);
            box_id = selRowData['box_id'];
            if(!box_id){
                showErrorDialog("","箱号数据异常！" + box_id);
                return false;
            }
            hld_evt_seq = selRowData['evt_seq_id_fk'];
            if(!hld_evt_seq){
                showErrorDialog("","数据异常！" + hld_evt_seq);
                return false;
            }

            inObj = {
                trx_id : VAL.T_XPBOXHLD ,
                action_flg : "R",
                box_id : box_id,
                evt_usr : VAL.EVT_USER,
                hld_evt_seq : hld_evt_seq
            };
            outObj = comTrxSubSendPostJson(inObj);
            if (outObj.rtn_code == VAL.NORMAL) {
                showSuccessDialog(box_id + "释放成功");
                crGrid.jqGrid("clearGridData");
                if (VAL.QUERY_ALL){
                	btnFunc.f1_func(); 
                }
            }
        }
    };

    /**
     * Bind button click action
     */
    var iniButtonAction = function(){
        btnQuery.f1.click(function(){
            btnFunc.f1_func();
        });
        btnQuery.f7.click(function(){
            btnFunc.f7_func();
        });
    };

    /**
     * grid  initialization
     */
    var iniGridInfo = function(){
        var grdInfoCM = [
            {name: 'box_id',         index: 'box_id'       ,   label: BOX_ID_TAG     , width: BOX_ID_CLM },
            {name: 'evt_seq_id_fk',  index: 'evt_seq_id_fk',   label: HOLD_SEQ_TAG  ,  width: SEQ_ID_CLM},
            {name: 'evt_usr',        index: 'evt_usr',         label: EVT_USR  ,       width: USER_CLM},
            {name: 'evt_timestamp',  index: 'evt_timestamp',   label: EVT_TIMESTAMP,   width: TIMESTAMP_CLM}
        ];
        controlsQuery.mainGrd.grdId.jqGrid({
            url:"",
            datatype:"local",
            mtype:"POST",
            height:300,
            width:600,
            shrinkToFit:false,
            scroll:true,
            rownumWidth : true,
            resizable : true,
            rowNum:40,
            loadonce:true,
            fixed:true,
            viewrecords:true,
            pager : controlsQuery.mainGrd.grdPgText,
            colModel: grdInfoCM
        });
     };

    /**
     * Other action bind
     */
    var otherActionBind = function(){
        // Reset size of jqgrid when window resize
        controlsQuery.W.resize(function(){
            toolFunc.resetJqgrid();
        });

        //Stop from auto commit
        $("form").submit(function(){
            return false;
        });

        controlsQuery.ppBoxIDInput.keydown(function(event){
            if(event.keyCode === 13){
                btnFunc.f1_func();
            }
        });
    };

    /**
     * Ini contorl's data
     */
    var iniContorlData = function(){
        toolFunc.clearInput();
    };

    /**
     * Ini view, data and action bind
     */
    var initializationFunc = function(){
        iniGridInfo();
        iniButtonAction();
        otherActionBind();

        toolFunc.resetJqgrid();
        toolFunc.iniOpeSelect();

        iniContorlData();
    };

    initializationFunc();
    
    function resizeFnc(){        
    	comResize(controlsQuery.W,controlsQuery.mainGrd.fatherDiv,controlsQuery.mainGrd.grdId);
    };                                                                                         
    resizeFnc();                                                                               
    domObj.$window.resize(function() {                                                         
    	resizeFnc();                                                                             
	});  
});

